import React, { useState, useEffect } from 'react';
import { Controlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/jsx/jsx';
import { Button } from 'antd';

const CodeEditor = () => {
  const [code, setCode] = useState(`
import { Button } from 'antd';

const App = () => {
  return (
    <div>
      <h1>Hello Ant Design!</h1>
      <Button type="primary">Click Me</Button>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));
`);

  const [preview, setPreview] = useState('');

  useEffect(() => {
    const transformedCode = `
      const React = require('react');
      const ReactDOM = require('react-dom');
      const { Button } = require('antd');

      ${code}
    `;

    const html = `
      <div id="root"></div>
      <script>
        ${transformedCode}
      </script>
    `;

    setPreview(html);
  }, [code]);

  return (
    <div style={{ display: 'flex' }}>
      <CodeMirror
        value={code}
        options={{
          mode: 'jsx',
          theme: 'material',
          lineNumbers: true,
        }}
        onBeforeChange={(editor, data, value) => {
          setCode(value);
        }}
      />
      <iframe
        srcDoc={preview}
        title="preview"
        style={{ width: '50%', height: '100vh', border: 'none' }}
      />
    </div>
  );
};

export default CodeEditor;
